package com.feature.core.config;

import java.sql.SQLException;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.core.Ordered;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.spring.boot.autoconfigure.properties.DruidStatProperties;

public class DruidDataSourceConfig implements BeanPostProcessor, Ordered {

	@Override
	public int getOrder() {
		return Ordered.LOWEST_PRECEDENCE;
	}

	@Override
	public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
		if (bean instanceof DruidDataSource) {
			setDefaultConfig((DruidDataSource) bean);
		} else if (bean instanceof DruidStatProperties) {
			setDefaultStatConfig((DruidStatProperties) bean);
		}
		return bean;
	}

	private void setDefaultConfig(DruidDataSource source) {
		source.setDriverClassName("com.mysql.jdbc.Driver");
		source.setInitialSize(10);
		source.setMinIdle(50);
		source.setMaxActive(300);
		source.setMaxWait(60000);
		source.setTimeBetweenEvictionRunsMillis(60000);
		source.setMinEvictableIdleTimeMillis(3600000);
		source.setValidationQuery("SELECT 'x'");
		source.setTestWhileIdle(true);
		source.setTestOnBorrow(false);
		source.setTestOnReturn(false);
		try {
			source.setFilters("stat,config,wall");
		} catch (SQLException e) {
			throw new RuntimeException(e);
		}
	}

	private void setDefaultStatConfig(DruidStatProperties stat) {
		DruidStatProperties.StatViewServlet config = stat.getStatViewServlet();
		config.setLoginUsername("admin");
		config.setLoginPassword("admin");

	}
}
